package com.gingko.duominuo.data

import com.gingko.duominuo.App
import com.gingko.duominuo.R
import com.gingko.duominuo.network.exception.ServerException
import com.gingko.duominuo.utils.loadRaw
import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.*

data class ApiResponse<T : Any?>(
    val code: Int,
    val error: String? = null,
    val `data`: T? = null,
)

fun <T> ApiResponse<T>.asResource(): Resource<T> {
    return if (this.isSuccess()) {
        Resource.Success(this.data)
    } else {
        Resource.Error(ServerException(this.code, getErrorMessage(this.code)))
    }
}

fun <T> ApiResponse<T>.isSuccess(): Boolean {
    return this.code == 200
}

private val errorMessage by lazy {
    Properties().apply {
        try {
            App.instance.loadRaw(R.raw.error_message).use { input ->
                BufferedReader(InputStreamReader(input)).use { bfr ->
                    load(bfr)
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}

private fun getErrorMessage(errorCode: Int): String {
    return errorMessage.getProperty(errorCode.toString()) ?: "请求失败，请稍后重试"
}
